using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using Common.Utilities;

namespace PdfLib.TextScraping
{
    /// <summary>
    /// 
    /// </summary>
    public class TableRowDetector
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pdfFilePath"></param>
        /// <param name="pageNum"></param>
        /// <param name="colLayouts"></param>
        /// <param name="requiredFields"></param>
        /// <param name="rowDetectorSettings"></param>
        /// <returns></returns>
        public static Dictionary<int,Range<float>> DetectTableRows(
            string pdfFilePath, int pageNum, 
            Dictionary<string,RectangleF> colLayouts, 
            List<string> requiredFields,
            TableRowDetectorInstruction rowDetectorSettings)
        {
            Dictionary<int,Range<float>> rowRanges=new Dictionary<int, Range<float>>();
            
            Range<float> headerRange=new Range<float>();
            headerRange.FromValue = -1f;
            headerRange.ToValue = -1f;
            foreach(string colHeader in colLayouts.Keys)
            {
                if(headerRange.FromValue<0)
                {
                    headerRange.FromValue = colLayouts[colHeader].Y;
                }
                else if (headerRange.FromValue > colLayouts[colHeader].Y)
                {
                    headerRange.FromValue = colLayouts[colHeader].Y;
                }
                if(headerRange.ToValue <0)
                {
                    headerRange.ToValue = colLayouts[colHeader].Y + colLayouts[colHeader].Height;
                }
                else if(headerRange.ToValue < colLayouts[colHeader].Y + colLayouts[colHeader].Height)
                {
                    headerRange.ToValue = colLayouts[colHeader].Y + colLayouts[colHeader].Height;
                }
            }

            List<PdfTextToken> txtTokens = PdfTextReader.ReadPageContentAsTokens(pdfFilePath, pageNum);
            List<PdfTextLine> lineTokens = PdfTextReader.CreateLines(txtTokens);
            lineTokens = PdfTextReader.MergeLines(lineTokens, PdfTextReader.LineSpacing);
            lineTokens.Sort();

            int rowNumber = 0;
            foreach(PdfTextLine lineToken in lineTokens)
            {
                if(lineToken.Rect.Y >=  headerRange.ToValue)
                {
                    rowNumber++;
                    Range<float> rowRange=new Range<float>();
                    rowRange.FromValue = lineToken.Rect.Y;
                    rowRange.ToValue = lineToken.Rect.Y + lineToken.Rect.Height;
                    rowRanges.Add(rowNumber, rowRange);
                }
            }
            return rowRanges;
        }
    }
}
